package com.speedchina.doormanager.controller;


import com.speedchina.doormanager.config.FileConfig;
import com.speedchina.doormanager.dao.SaomaDTO;
import com.speedchina.doormanager.enums.ResultEnum;
import com.speedchina.doormanager.exception.GlobalException;
import com.speedchina.doormanager.service.SaomaService;
import com.speedchina.doormanager.util.FileUtil;
import com.speedchina.doormanager.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class MainController {

    private Logger log = LoggerFactory.getLogger(MainController.class);

    @Autowired
    private SaomaService saomaService;


    @GetMapping("/")
    public String index() {
        return "index";

    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/upload/photo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public ResultVO uploadPhoto(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new GlobalException(ResultEnum.UPLOAD_PHOTO_IS_EMPTY);
        }
        String fileName = file.getOriginalFilename();
        log.info(fileName);
        try {
            FileUtil.uploadFile(file.getBytes(), FileConfig.FILEPATH, fileName);
        } catch (Exception e) {
            throw new GlobalException(ResultEnum.UPLOAD_PHOTO_ERROR);
        }
        Map<String, String> map = new HashMap<>(2);
        map.put("url", FileConfig.FILE_PREFIX + fileName);
        return ResultVO.success(map);
    }

    /**
     * 扫码页
     *
     * @return
     */
    @GetMapping("/saoma/{doorPlateId}")
    public String saoma(@PathVariable("doorPlateId") String doorPlateId, Model model) {
        SaomaDTO saomaDTO = saomaService.findByDoorPlateId(doorPlateId);

        model.addAttribute("saomaDTO", saomaDTO);
        return "fenye/admin-sao-detail";

    }

    /**
     * 个人中心
     *
     * @return
     */
    @GetMapping("/userIndex")
    public String userIndexPage() {
        return "fenye/gerenzhongxin";
    }
}
